package cs2340.g21.wms;

import java.util.Calendar;
import java.util.Locale;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays a login screen to the user, with a button to be
 * taken to a register page as well as a language option
 */
public class LoginActivity extends WMSActivity {

    private static final String LOG_TAG = "debugger";
    
    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    
    //the "database" standin
    private Coordinator coordinator;
    
    //language options
    private String[] languages = {"English","Русский","Français"};
    Locale mLocale = new Locale("en");
    int selectedLang = 0;
    
    @Override
    /*
     * Sets up coordinator, forms, buttons
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        coordinator = new Coordinator();
        Session session = new Session();
        Log.d(LOG_TAG, "from data");
        coordinator = session.readSession(this);
        if(getIntent().getExtras() != null && coordinator == null){
            Log.d(LOG_TAG, "from bundle");
            coordinator = (Coordinator) getIntent().getExtras().getSerializable("cs2340.g21.wms.coordinator");
            selectedLang = getIntent().getExtras().getInt("selectedLang");
        }else if(coordinator == null){
            Log.d(LOG_TAG, "new coord");
            coordinator = new Coordinator();
        }
        
        setContentView(R.layout.activity_login);

        // Set up the login form.
        mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(mEmail);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView textView, int id,
                            KeyEvent keyEvent) {
                        if (id == R.id.login || id == EditorInfo.IME_NULL) {
                            attemptLogin();
                            return true;
                        }
                        return false;
                    }
                });

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        attemptLogin();
                    }
                });
        findViewById(R.id.register_button).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mEmail = mEmailView.getText().toString();
                        mPassword = mPasswordView.getText().toString();
                        Intent intent = new Intent();
                        intent.putExtra("cs2340.g21.wms.coordinator", coordinator);
                        intent.putExtra("email", mEmail);
                        intent.putExtra("pass", mPassword);
                        intent.setClass(LoginActivity.this, RegisterActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
        
        findViewById(R.id.language_button).setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder langMenu = new AlertDialog.Builder(LoginActivity.this);
                        langMenu.setTitle(R.string.dialog_change_language);
                        langMenu.setSingleChoiceItems(languages, selectedLang, new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog, int choice){
                                if(choice == 0){
                                    mLocale = new Locale("en");
                                    selectedLang = 0;
                                }else if(choice == 1){
                                    mLocale = new Locale("ru");  
                                    selectedLang = 1;
                                }else if(choice == 2){
                                    mLocale = new Locale("fr");
                                    selectedLang = 2;
                                }
                            }
                        });
                        langMenu.setPositiveButton(R.string.prompt_confirm, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Locale.setDefault(mLocale); 
                                Configuration config = new Configuration();
                                config.locale = mLocale;
                                getBaseContext().getResources().updateConfiguration(config, 
                                getBaseContext().getResources().getDisplayMetrics());
                                Intent intent = getIntent();
                                intent.putExtra("cs2340.g21.wms.coordinator", coordinator);
                                intent.putExtra("selectedLang", selectedLang);
                                finish();
                                startActivity(intent);
                            }
                        });
                        langMenu.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                        AlertDialog langDialog = langMenu.create();
                        langDialog.show();
                    }
                });
    }
    
    public void notifyAdmin(View view){
        AlertDialog.Builder notifyBuild = new AlertDialog.Builder(this);
        notifyBuild.setTitle("Contact admins");
        final EditText input = new EditText(this);
        String email = getIntent().getStringExtra(EXTRA_EMAIL);
        input.setText(email);
        notifyBuild.setView(input);
        
        notifyBuild.setPositiveButton(R.string.prompt_confirm, new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String email = input.getText().toString();
                if(!coordinator.checkEmailAvailable(email)){
                    Note n = new Note("unlock", coordinator.getAccount(coordinator.getAccountId("admin@wms.com")), 
                                      coordinator.getAccount(coordinator.getAccountId(email)), Calendar.getInstance());
                    Log.d(LOG_TAG, "making note with msg: "+n.getMessage()+" and email "+coordinator.getAccount(coordinator.getAccountId(email)).getEmail());
                    coordinator.addAdminNote(n);
                }else{
                    input.setError(getString(R.string.error_invalid_email));
                }
            }
        });
        
        notifyBuild.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                
            }
            
        });
        
        notifyBuild.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE
                                    : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE
                                    : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            
            if(coordinator.checkEmailAvailable(mEmail)){
                return false;
            }
            User u = coordinator.getAccount(coordinator.getAccountId(mEmail));
            if (u != null){
                if(!u.isLocked()){
                    if(u.checkPass(mPassword)){
                        coordinator.setUser(mEmail);
                        coordinator.getAccount(coordinator.getAccountId(mEmail)).resetLogin();
                        return true;
                    }
                }
            }
            return false;
            
            /*try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }*/
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Intent intent = new Intent();
                intent.putExtra("cs2340.g21.wms.coordinator", coordinator);
                if(coordinator.getAccount(coordinator.getAccountId(mEmail)).isAdmin()){
                    Log.d(LOG_TAG, "admin detected");
                    intent.setClass(LoginActivity.this, AdminControlsActivity.class);
                    startActivity(intent);
                    finish();
                }else{
                    Log.d(LOG_TAG, "admin not detected");
                    intent.setClass(LoginActivity.this, HomeScreenActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else {
                if(coordinator.checkEmailAvailable(mEmail)){
                    mEmailView.setError(getString(R.string.error_invalid_email));
                }else if(coordinator.getAccount(coordinator.getAccountId(mEmail)).isLocked()){
                    mEmailView.setError(getString(R.string.error_account_locked));
                    mEmailView.requestFocus();
                }else{
                    mPasswordView
                            .setError(getString(R.string.error_incorrect_password) + ", "+
                                     coordinator.getAccount(coordinator.getAccountId(mEmail)).getAttempts() +" attempts left");
                    mPasswordView.requestFocus();
                }
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
    
    protected void onPause(){
        super.onPause(coordinator);
    }
}
